package com.cgx.tablet.beeper.utils.pay;

import android.util.Log;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

/**
 * 支付宝支付工具类
 * Created by admin on 2016/10/21.
 */
public class AliPayUtil {

    // 商户PID
    private static final String ALI_APP_ID = "2018042302595103";
//    private static final String ALI_APP_ID = "2017062707578072";
    // 商户私钥
    private static final String ALI_RSA_PRIVATE = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCDhjVYzahJDdQT1VQTia586DxXVWad6VfCbAYC5CGit1K9RstAYpngOs5FfW2Wsn1iLJlGaluylJcojE897/XZRv3NfuT625vMDbifqTbaafrPMsDDyu/" +
        "j010KMjtqoDPCj0ODOKqK5Qon8idjCGzX1IWFFY2qgqDOef3Fn77/hgbNvzBTrOJRDrbeXTRlWU0IOdxSLtUCCF5/" +
        "t+/T6KAAG9HW/TKjZK4irmPm2PJtyh6Nuvvs/FHSSmXK0poAeUxG1ErPBwAwnp+79+Tu/" +
        "NM859wtvOPUAuhhpozRpsfGlo71p8ddbwisctsBu7NhClUZGOgLJllUXrK41K6JsML5AgMBAAECggEAWock7vPXUjlPcTtTvIL29AiRh/" +
        "dDQ4vaGPtrg8/siugt7hPtUGrNyTYQxmnX5XMDtHBIK9yHMzrtdD5nSJWDHcOsbCZci4JfESucmWDKXbm2pakkX1+ukJzqHFuI5BJSricX7Bkz4ZhWzjnx/" +
        "EtPR5uDL6AvO17gOl5jWwRiXdOtWIYDIG5/BF2bnvjHl9mCbH+lj5B4lTHS/OJjuEexRkTnlTEIy0Ay7zUcK+" +
        "Ty3F9TEZLE+S5yA+d2eWxWomlfr+xAMOSZohLxd5VoXAu2UmZ1jDq+/5iWytHDPuEhnElbFeoQy86e2G3OIGIo+" +
        "5cX1TFsLixpmlgCeg483KIzBQKBgQDZdOrPw8jJ/Q8FN/SJT3ESR1txlgjcDrOmRzZDGDuwZfCt2PZuNKmX2PjsQqs862C9cRNM+YUtZQNazRatIH6/" +
        "BajU94XtEBNwwBlSIL2lL7/MZSBjNTikOBqU5iexG+r5isq2GfBVPJmy/aDyoUaQTLTt2omwpTx4wLZjIwu9lwKBgQCa1hyswQdNEtyU+GJPFoOIr" +
        "cEpRtNwItXSiEemDirEihnmfX97vO8vDr/if6FEhWyQ9x7buPayF+0kDxQQy1gGx8dg58gc+DxNOUT+OlRYmOh6R4o3QAXzFEdiS/" +
        "uqnvZuVj09c3bsGlk60ofPYBZJ4P1nFMWifP2GvIrVBKm17wKBgQCiz7LvE7tF4D5aveZM2DnkYaDJjnfbqvY+" +
        "zJqH6aDnFav5vbPkF3HSyxS0b8Ydum2X6Q12WGup7TNxzJPp06aSBv69VQXk1GB5zpomr3TONM35js2M+" +
        "dAKxCbCzP9yz2BCrfPQG+OhLdo19UeH4dAfQg9E9paYt15rWn40A41KyQKBgB/cAKh3S3ZLdEHe3fOiEUyVXBKPNUB0moSob/" +
        "22Goy4Ud4AYrPmS1zmbws+8cL0pUMq5hmV9ITusWfjBmDyRlmWz+qbpqx3U4kcSJr7C5HzXJqUj9cQgGjk+" +
        "k86jT0tWk2XxyAW2xh3z3ZwDWvZPJzVA68rMgNeLpiDwRlVzUnXAoGBAIP9oXGvGtXR5uab4KFzP9P8hOVve9O1" +
        "lZw0HYpQpYTQEaAMrHch8ONgCrPLWFOFL4dUO/1AJypLHmZY4BvycCMg2aIDT7kqzfg1xiVPGG+KWG62czG+" +
        "t5Hm9ItXbFU2FynyyASf7/tK5SwtDnfwv4V/xKtUh0wLLYMvVSjpZSTh";

//    private static final String ALI_RSA_PRIVATE ="-----BEGIN PRIVATE KEY-----" +
//            "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCPFs33Ccts9Awb" +
//            "92le07WafGvMrtZMz5SVlIo70AsjE0/T7DSjecc/xq3yjobEQ7mTRED2ZXDMIse8" +
//            "VXdrIdvx9EfmOZPIgEdWeDpLV5WjTGdpQzzQ6iubZUNOcrHzO1gxmY+O5dXzA97o" +
//            "ICnpLOI/5Z/lzWJ8zJZgowOTvM9ZEzWDCLqC6Qprr5OcM0Mhp3TtfvviyCvPi995" +
//            "gCCe9B3OGfl6GBSJOPZZFsq7qPM5wMWdtBAPPa/tFCGFl+n7KFkSZF8aE4Z7QxzX" +
//            "2gQrj5QJAjc180HzT80II2zcpPBr8XvIB3Ip4LCBideIGFs0eU6GcfLNHmRIXh+n" +
//            "s0lTkCKXAgMBAAECggEAPJFdm61Es5jWK1xd+OrKm1sBUoHLanYPogVfQhQ9Mpqx" +
//            "FraMTYp1wdQ6u0qDVz6HpgOlL+ceiPpL67eNtgZ+EHvjl1tV5/AMwlhf7JZlW9sy" +
//            "hscUTiZhUQTbKbC5DIlZOp2Su90j5BsGVuGOfAootv1e4qo+fy8mlD9Me1PXvQ8V" +
//            "vCenALPASPHWONsJTIyzWwZzrs7X/OJF1xSZV1Hu+P1ZkJG1G3Izaya0LRbib8dT" +
//            "xrfEJ8W+eZ+o/xZixUg2n4VOPawxUfIpEcAwz/ZxMVUALqNfW+zXPSeGjQgplv7U" +
//            "qrBa/cwYeCOAhaRQPBxuqFqymKA3SrCGuvxJAzJH0QKBgQDdeaHDurbO0Bnhuo/y" +
//            "s2cv7KvTcQuxLvl5IG6efSI04SZPr2QP1KeEZbGpMf7F73hx78MJdgox6Dl0ZwKW" +
//            "HRzrfxETqfM7nFMaXcNgqbgWEfYPBOl6wE/PgWdZ1vZ9jXxh+6j5wyRK7uTuNJo9" +
//            "k/djyKyCFuf4CayZpbprh8vizwKBgQClZQjq8rs50f5CHK/amXBp/hE/hYtb7W5p" +
//            "i/6wJ2tAoZwSt6dVIxd3wIcpYjar81h9VdD1eaHgv47qhGKvOHZ+pBNDJFvEtbEz" +
//            "yLqZuU9rqIgyrZrTyKSVVJ5Oif+PGxn0757ggz2383LOKooRQdtSczHalYmGEPqB" +
//            "bQA4pw3VuQKBgBzDEgX4NotvLR1KfC05rTnlE393G9ybzBw14QfGGm4hmzcYAPep" +
//            "V0PzbPobGwobilnJmFufL73BecyrIAPcrgfLTa1vEb55E7XF3XytLdH37SuQKL4f" +
//            "QX4iQQjCyOoPOMsEwrIE7K6qjaJ9xFYg5CzaP8T5MpDcuMSPaEFUtl6zAoGAEqXC" +
//            "jKLTYyB+9zs+xHm6R+kCTtQiszmg0jubeobnO8E81ItqTVoIglLtqkfNfDOSjYcI" +
//            "aTTOgIV4eo50hebqzTp4hYBq7FHD6d++0igngS7eNECIjUo47DE/LAG5E4xtr8T4" +
//            "d720TrIfBombSXjQXopoW4mymK//XmpItRp4n9kCgYEAxZERl8qUh4S9l2cJTUTn" +
//            "XFurci2KiNOZscSf5xUKJ2x83X0n1msEUoV6i08xiG8qIFdLKYMwWEisgQ7cqGeD" +
//            "1fwB8HkSPbYUqI+wv5wdw04/O7Nr8GqZP+XtB0P9JM5YnQYukMveHGGAR6YkQYDN" +
//            "P1igMXIDMxXtszUS0gwqzvk=";
    // 回调
    private static final String ALI_NOTIFY_URL = "http://led.linkfun.cc:8092/notify/alipay";
    private static final String ALGORITHM = "RSA";
    private static final String SIGN_ALGORITHMS = "SHA256WithRSA";
    private static final String DEFAULT_CHARSET = "UTF-8";

    /**
     * 创建订单信息
     *
     * @param subject  商品名称
     * @param body     商品详情
     * @param order_sn 订单号
     * @param price    价格
     * @return 订单信息
     */
    public static String getPayInfo(String subject, String body, String order_sn, String price) {
//        price = "0.01";
        Map<String, String> params = buildOrderParamMap(subject, body, order_sn, price);
        String orderParam = buildOrderParam(params);
        String sign = getSign(params);
        return orderParam + "&" + sign;
    }

    private static Map<String, String> buildOrderParamMap(String subject, String body, String order_sn, String price) {
        Map<String, String> keyValues = new HashMap<>();
        keyValues.put("app_id", ALI_APP_ID);
        keyValues.put("method", "alipay.trade.app.pay");
        keyValues.put("charset", "utf-8");
        keyValues.put("sign_type", "RSA2");
        keyValues.put("timestamp", getCurrentTime());
        keyValues.put("version", "1.0");
        keyValues.put("notify_url", ALI_NOTIFY_URL);
        keyValues.put("biz_content",
                "{\"timeout_express\":\"30m\"," +
                        "\"product_code\":\"QUICK_MSECURITY_PAY\"," +
                        "\"total_amount\":\"" + price + "\"," +
                        "\"subject\":\"" + subject + "\"," +
                        "\"body\":\"" + body + "\"," +
                        "\"out_trade_no\":\"" + order_sn + "\"}");
        Log.e("==sign==", keyValues.toString());
        return keyValues;
    }

    private static String getCurrentTime() {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
        Date date = new Date(System.currentTimeMillis());
        return dateFormat.format(date);
    }

    /**
     * 构造支付订单参数信息
     */
    private static String buildOrderParam(Map<String, String> map) {
        List<String> keys = new ArrayList<>(map.keySet());
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < keys.size() - 1; i++) {
            String key = keys.get(i);
            String value = map.get(key);
            sb.append(buildKeyValue(key, value, true));
            sb.append("&");
        }
        String tailKey = keys.get(keys.size() - 1);
        String tailValue = map.get(tailKey);
        sb.append(buildKeyValue(tailKey, tailValue, true));
        return sb.toString();
    }

    /**
     * 构造支付订单参数信息
     */
    private static String buildOrderParamOrg(Map<String, String> map) {
        List<String> keys = new ArrayList<>(map.keySet());
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < keys.size() - 1; i++) {
            String key = keys.get(i);
            String value = map.get(key);
            sb.append(key);
            sb.append("=");
            sb.append(value);
            sb.append("&");
        }
        String tailKey = keys.get(keys.size() - 1);
        String tailValue = map.get(tailKey);
        sb.append(tailKey);
        sb.append("=");
        sb.append(tailValue);
        return sb.toString();
    }

    /**
     * 拼接键值对
     */
    private static String buildKeyValue(String key, String value, boolean isEncode) {
        StringBuilder sb = new StringBuilder();
        sb.append(key);
        sb.append("=");
        if (isEncode) {
            try {
                sb.append(URLEncoder.encode(value, "UTF-8"));
            } catch (UnsupportedEncodingException e) {
                sb.append(value);
            }
        } else {
            sb.append(value);
        }
        return sb.toString();
    }

    /**
     * 对支付参数信息进行签名
     */
    private static String getSign(Map<String, String> map) {
        List<String> keys = new ArrayList<>(map.keySet());
        // key排序
        Collections.sort(keys);
        StringBuilder authInfo = new StringBuilder();
        for (int i = 0; i < keys.size() - 1; i++) {
            String key = keys.get(i);
            String value = map.get(key);
            authInfo.append(buildKeyValue(key, value, false));
            authInfo.append("&");
        }
        String tailKey = keys.get(keys.size() - 1);
        String tailValue = map.get(tailKey);
        authInfo.append(buildKeyValue(tailKey, tailValue, false));
        String oriSign = sign(authInfo.toString());
        String encodedSign = "";
        try {
            encodedSign = URLEncoder.encode(oriSign, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return "sign=" + encodedSign;
    }

    /**
     * 对订单信息进行签名和做URL编码
     * 特别注意，这里的签名逻辑需要放在服务端，切勿将私钥泄露在代码中！
     *
     * @param content 待签名订单信息
     * @return 签名后订单信息
     */
    private static String sign(String content) {
        try {
            PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(
                    AliBase64.decode(ALI_RSA_PRIVATE));
            KeyFactory keyf = KeyFactory.getInstance(ALGORITHM);
            PrivateKey priKey = keyf.generatePrivate(priPKCS8);
            java.security.Signature signature = java.security.Signature
                    .getInstance(SIGN_ALGORITHMS);
            signature.initSign(priKey);
            signature.update(content.getBytes(DEFAULT_CHARSET));
            byte[] signed = signature.sign();
            return AliBase64.encode(signed);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

}
